package com.imgpro.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.imgpro.Context.BaseContext;
import com.imgpro.Exception.ServerBusyException;
import com.imgpro.constants.PromoteConstant;
import com.imgpro.constants.RedisConstant;
import com.imgpro.entity.UserUrl;
import com.imgpro.mapper.UserUrlMapper;
import com.imgpro.service.CommonService;
import com.imgpro.service.UserUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.imgpro.Utils.DoubaoUtil.callVisionApi;

@Service
@Slf4j
public class UserUrlServiceImpl implements UserUrlService {

    @Autowired
    private UserUrlMapper userUrlMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CommonService commonService;


    private static final DefaultRedisScript<Long> TOAI_SCRIPT;
    static{
        TOAI_SCRIPT = new DefaultRedisScript<>();
        TOAI_SCRIPT.setLocation(new ClassPathResource("toAi.lua"));
        TOAI_SCRIPT.setResultType(Long.class);
    }

    //    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private static final ExecutorService SECKILL_EXECUTOR = Executors.newSingleThreadExecutor();


    @PostConstruct
    private void init(){
        SECKILL_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private UserUrlService proxy ;


    private class VoucherOrderHandler implements Runnable{
//        获取消息队列里的东西，顺便判断消息获取是否成功

//        判断消息获取是否成功

//        如果获取失败，说明没有消息，继续下一次循环

        //        如果获取成功，可以下单，然后可以ack确认
        String queueName = RedisConstant.QUEUE_NAME;

        @Override
        public void run() {
            while(true){
                try{
                    List<MapRecord<String, Object, Object>> voucherOrder = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    if(voucherOrder == null || voucherOrder.isEmpty()){
                        Thread.sleep(50);
                        continue;
                    }
                    MapRecord<String, Object, Object> record = voucherOrder.get(0);
                    Map<Object, Object> value = record.getValue();

//                    获取用户url对象
                    UserUrl userUrl =  BeanUtil.fillBeanWithMap(value, new UserUrl(), true);
//                     调用豆包ai，获取对图片的友好评论哈哈哈
                    String apiResponse = callVisionApi(PromoteConstant.DEFAULT_PROMOTE, userUrl.getUrlLow());

                    userUrl.setComment(apiResponse);
                    userUrl.setCreatedAt(LocalDateTime.now());
//                   存入数据库我敲
                    saveToUserUrl(userUrl);

                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());


                } catch (Exception e) {
                    log.error("出现ai评论异常" + e.getMessage());
                    try {
                        handlePendingList();
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
        private void handlePendingList() throws InterruptedException {
            while(true){
                try{
                    List<MapRecord<String, Object, Object>> voucherOrder = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    if(voucherOrder == null || voucherOrder.isEmpty()){
                        break;
                    }
                    MapRecord<String, Object, Object> record = voucherOrder.get(0);
                    Map<Object, Object> value = record.getValue();

                    //                    获取用户url对象
                    UserUrl userUrl =  BeanUtil.fillBeanWithMap(value, new UserUrl(), true);
//                     调用豆包ai，获取对图片的友好评论哈哈哈
                    String apiResponse = callVisionApi(PromoteConstant.DEFAULT_PROMOTE, userUrl.getUrlLow());


                    userUrl.setComment(apiResponse);
                    userUrl.setCreatedAt(LocalDateTime.now());
//                   存入数据库我敲
                    saveToUserUrl(userUrl);
//                    如果获取成功，可以下单

                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());


                } catch (Exception e) {
                    log.error("出现订单异常,处理pendingList异常");
                    Thread.sleep(50);
                }
            }


        }
    }





    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveToUserUrl(UserUrl userUrl) {

        userUrlMapper.insertUserUrl(userUrl);

        log.info("照片保存成功，保存到数据库");

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveToUserUrl(String url) {

        UserUrl userUrl = UserUrl.builder()
                .userId(BaseContext.getCurrentId())
                .url(url)
                .urlLow("还是测试上传功能，但是没有压缩过程，单纯测试功能罢了")
                .createdAt(LocalDateTime.now())
                .build();

        userUrlMapper.insertUserUrl(userUrl);

        log.info("照片保存成功，保存到数据库");

    }

    @Override
    public void PreSaveToUserUrl(String url, String url_low) throws Exception {

        Long result = stringRedisTemplate.execute(
                TOAI_SCRIPT,
                Collections.emptyList(),
                url,
                url_low,
                commonService.getCurrentUUid()
        );

        if(result != 0){
            throw new ServerBusyException("当前服务器繁忙，请等待一会再试");
        }
    }
}
